import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators, AbstractControl } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';

// services
import { ConstantService } from '../../../../../core/services/constant.service';
import { ServerService } from '../../../../../core/services/server.service';
import { StorageService } from '../../../../../core/services/storage.service';

@Component({
    selector: 'app-user-management',
    templateUrl: './user-management.component.html',
    styleUrls: ['./user-management.component.css']
})
export class UserManagementComponent implements OnInit {
    userForm: FormGroup;                   // 用户表单
    isVisible: boolean = false;            // 是否显示modal
    isConfirmLoading: boolean = false;     // modal中点击保存的时候的过渡效果
    isViewStateUpdate: boolean = false;    // 页面是否是更新状态
    schoolId: string;                      // 学校id
    userList: object[] = [];               // 全部用户
    gradeList: object[] = [];              // 全部角色列表
    classList: object[] = [];              // 全部角色列表
    subjectList: object[] = [];            // 全部角色列表
    roleList: object[] = [];               // 全部角色列表
    _current: number = 1;                  // 当前页
    _pageSize: number = 10;                // 每页数量
    _total: number = 1;                    // 数据总数
    _loading: boolean = true;              // 加载动画

    constructor(
        private fb: FormBuilder,
        private constant: ConstantService,
        private server: ServerService,
        private storage: StorageService,
        private message: NzMessageService
    ) {
        /**
         * 初始化用户表单
         * username: 用户名
         * name: 用户真实姓名
         * sex: 用户性别 1 男 2 女
         * gradeIds: 年级id
         * classIds: 班级id
         * subjectIds: 负责科目id
         * roleId: 角色权限id
         */
        this.userForm = this.fb.group({
            _id: [null],
            username: [null, [Validators.required, Validators.minLength(11), Validators.maxLength(11)]],
            name: [null, [Validators.required, Validators.minLength(2), Validators.maxLength(6)]],
            sex: ['1', Validators.required],
            gradeIds: [null, Validators.required],
            classIds: [null, Validators.required],
            subjectIds: [null, Validators.required],
            roleId: [null, Validators.required]
        });
        this.schoolId = this.storage.getItem(this.constant.storage.currentUser)['schoolId']['_id'];
    }

    ngOnInit() {
        this.getAllUsers();
    }

    /**
     * 显示modal,添加或更新用户
     * @param id 
     */
    async showModal(id) {
        this.isVisible = true;
        // 首先获取年级列表,班级列表,科目列表,角色列表
        await Promise.all([this.getAllGrades(), this.getAllClasses(), this.getAllSubjects(), this.getAllRoles()]);
        if (id) {
            this.isViewStateUpdate = true;
            const result = await this.server.fetch(this.constant.api.manage.user.findOne, { id });
            if (result) {
                this.userForm.setValue({
                    _id: result.data._id,
                    username: result.data.username,
                    name: result.data.name,
                    sex: String(result.data.sex),
                    gradeIds: result.data.gradeIds,
                    classIds: result.data.classIds,
                    subjectIds: result.data.subjectIds,
                    roleId: result.data.roleId
                });
            }
        } else {
            this.isViewStateUpdate = false;
        }
    }

    /**
     * 获取年级列表
     * @param schoolId 
     */
    async getAllGrades() {
        const param = {
            schoolId: this.schoolId,
            page: 1,
            limit: 10000
        };
        const allGrades = await this.server.fetch(this.constant.api.manage.grade.findAll, param);
        if (allGrades) {
            this.gradeList = allGrades.data.data;
        }
    }

    /**
     * 获取班级列表
     * @param schoolId 
     */
    async getAllClasses() {
        const param = {
            schoolId: this.schoolId,
            page: 1,
            limit: 10000
        };
        const allClasses = await this.server.fetch(this.constant.api.manage.classM.findAll, param);
        if (allClasses) {
            this.classList = allClasses.data.data;
        }
    }

    /**
     * 获取科目列表
     * @param schoolId 
     */
    async getAllSubjects() {
        const param = {
            schoolId: this.schoolId,
            page: 1,
            limit: 10000
        };
        const allSubjects = await this.server.fetch(this.constant.api.manage.subject.findAll, param);
        if (allSubjects) {
            this.subjectList = allSubjects.data.data;
        }
    }

    /**
     * 获取角色列表
     * @param schoolId 
     */
    async getAllRoles() {
        const param = {
            schoolId: this.schoolId,
            page: 1,
            limit: 10000
        };
        const allRoles = await this.server.fetch(this.constant.api.manage.role.findAll, param);
        if (allRoles) {
            this.roleList = allRoles.data.data;
        }
    }

    /**
     * 关闭modal
     * @param e 
     */
    handleCancel(e): void {
        this.userForm.reset({
            _id: null,
            username: null,
            name: null,
            gradeIds: [],
            classIds: [],
            subjectIds: [],
            sex: '1',
            roleId: null
        });
        this.isVisible = false;
    }

    // 获取表单项
    getFormControl(name): AbstractControl {
        return this.userForm.controls[name];
    }

    /**
     * 保存 || 更新
     * @param e 
     * @param school 
     */
    async handleOk(e, user): Promise<void> {
        const phone_regexp = /^[1][3,4,5,7,8][0-9]{9}$/;
        if (!phone_regexp.test(user.username)) {
            this.message.error('抱歉,用户名输入有误,请重新输入');
            return;
        }
        user.schoolId = this.schoolId;
        this.isConfirmLoading = true;
        // 保存
        const result = await this.server.fetch(this.constant.api.manage.user[this.isViewStateUpdate ? 'update' : 'save'], user);
        if (result) {
            this.message.success('保存用户成功');
            if (!this.isViewStateUpdate) {
                // 清空表单
                this.userForm.reset();
                this.userForm.controls['sex'].setValue('1');
            }
            this.isConfirmLoading = false;
            this.getAllUsers();
            this.isVisible = false;
        } else {
            this.isConfirmLoading = false;
        }

    }

    /**
     * 获取全部班级列表
     */
    async getAllUsers(): Promise<void> {
        const param = {
            schoolId: this.schoolId,
            page: this._current,
            limit: this._pageSize
        };
        const allUsers = await this.server.fetch(this.constant.api.manage.user.findAll, param);
        if (allUsers) {
            this.userList = allUsers.data.data;
            this._total = allUsers.data.count;
            this._loading = false;
            // 装换数据
            if (this.userList.length > 0) {
                for (let user of this.userList) {
                    let gradeStr = [],
                        classStr = [],
                        subjeStr = [];
                    if (user['gradeIds'].length > 0) {
                        for (let grade of user['gradeIds']) {
                            gradeStr.push(grade.name);
                        }
                        user['gradeIds'] = gradeStr.join(' | ');
                    } else {
                        user['gradeIds'] = '暂无';
                    }
                    if (user['classIds'].length > 0) {
                        for (let c of user['classIds']) {
                            classStr.push(c.name);
                        }
                        user['classIds'] = classStr.join(' | ');
                    } else {
                        user['classIds'] = '暂无';
                    }
                    if (user['subjectIds'].length > 0) {
                        for (let subject of user['subjectIds']) {
                            subjeStr.push(subject.name);
                        }
                        user['subjectIds'] = subjeStr.join(' | ');
                    } else {
                        user['subjectIds'] = '暂无';
                    }
                }
            }
        } else {
            this._loading = false;
        }
    }
}
